package org.ch02.test00.demo10.myWork;

import java.lang.reflect.Field;

/**
 * @author CSY
 * @date 2025 - 03 - 19
 */
public class BeanUtil<T,R> {
    /**
     * 设置何意对象的属性值
     * @param bean 对象
     * @param propertyName 属性名称
     * @param value 值
     */
    public void setProperty(T bean, String propertyName, R value){
        Class<?> clazz = bean.getClass();
        try {
            Field declaredField = clazz.getDeclaredField(propertyName);
            declaredField.setAccessible(true);
            declaredField.set(bean, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取任意对象的属性值
     * @param bean
     * @param propertyName
     * @return
     */
    public Object getProperty(T bean, String propertyName){
        Class<?> clazz = bean.getClass();
        Field declaredField = null;
        try {
            declaredField = clazz.getDeclaredField(propertyName);
            declaredField.setAccessible(true);
            return declaredField.get(bean);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制某个对象的属性值到另一个对象中
     * @param source
     * @param target
     */
    public void copyProperties(T source, T target){
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();
        Field[] sourceFields = sourceClass.getDeclaredFields();
        Field[] targetFields = targetClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            sourceFields[i].setAccessible(true);
            targetFields[i].setAccessible(true);
            sourceFields[i].setAccessible(true);
            try {
                Object obj = sourceFields[i].get(source);
                targetFields[i].set(target, obj);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
